;((doc, storage, location, Socket) => {
  const lists = doc.querySelector('#list')
  const message = doc.querySelector('#message')
  const send = doc.querySelector('#send')
  
  const ws = new Socket('ws:localhost:8000')
  let username = ''
  const init = () => {
    bindEvents()
  }
  
  function bindEvents() {
    send.addEventListener('click', handleSendClick, false)
    ws.addEventListener('open', handleOpen, false)
    ws.addEventListener('message', handleMessage, false)
    ws.addEventListener('close', handleClose, false)
    ws.addEventListener('error', handleError, false)
  }
  
  function handleOpen(e) {
    // 进入聊天室，获取用户名
    console.log('open', e)
    username = storage.getItem('uname')
    if (!username) {
      location.href = 'entry.html'
    }
  }
  
  function handleMessage(event) {
    // 接收服务器的消息
    console.log('message:', JSON.parse(event.data).message)
    lists.appendChild(createmsg(JSON.parse(event.data)))
  }
  
  function createmsg(data) {
    const {user, dateTime, message} = data
    const li = doc.createElement('li')
    li.innerHTML = `${user} ${dateTime} ${message}`
    return li
  }
  
  function handleClose() {
    console.log('close')
  }
  
  function handleError(e) {
    console.log('error', e)
  }
  
  // 发送消息
  function handleSendClick() {
    // 点击发送消息给服务器
    const msg = message.value
    console.log(msg);
    if (msg.trim().length <= 0) {
      alert('消息不能为空')
      return
    }
    ws.send(JSON.stringify({user: username, dateTime: new Date().toLocaleString(), message: msg}))
    message.value = ''
  }
  
  init()
  
})(document, localStorage, location, WebSocket)
